<template>
  <operation @add="add">公告发布</operation>
  <el-table :data="formData" style="width: 100%">
    <el-table-column label="公告标题" prop="title" />
    <el-table-column label="公告内容" prop="content" />
    <el-table-column align="right">
      <template #header>
        <el-input v-model="search" size="small" placeholder="Type to search" />
      </template>
      <template #default="scope">
        <el-button size="small" type="primary" @click="handleEdit( scope.row.id)">
          Edit
        </el-button>
        <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row.id)">
            Delete
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页栏 -->
  <div class="pagination">
    <el-pagination background :default-page-size="listCount" layout="prev, pager, next" :total="totalCount"
                   @current-change="handleCurrentChange" />
  </div>
</template>

<script setup>
import Operation from "../components/operation.vue";
// 导入Operation组件
import {computed, inject, ref, watch} from 'vue'
import {useRouter} from "vue-router";
const router = useRouter()
const $root = inject("$root")
const $axios = inject("$axios")
// 页面表格数据
let formData = ref([])
//定义每页显示数据条数
let listCount = 3
//定义总数据条数,默认0
let totalCount = ref(0)
const getPageData =(pageNo = 1)=> {
  // 发送请求获取页面数据
  $axios.get($root + `/notice/?page=${pageNo}&page_size=${listCount}`)
      .then(r => {
        if (r.data.code == 200) {
          console.log(r)
          formData.value = r.data.data.data
          totalCount = r.data.data.total_count
        }
      })
}
//分页栏功能
const handleCurrentChange = (e) => {
  // e为当前页
  getPageData(e)
}
//添加数据
const add = () => {
  router.push(`/home/noticeDetail`)
}
//编辑数据
const handleEdit = (id) => {
  router.push(`/home/noticeDetail/${id}`)
}
// 删除数据方法
const handleDelete = (id) => {
  $axios.post($root+`/notice/delete/${id}/`)
      .then(r => {
        if (r.data.code == 200) {
          getPageData()
          ElMessage({
            message: '删除成功',
            type: 'success',
          })
        }
        else {
          ElMessage.error('删除失败')

        }
      })
}

watch(() => router.currentRoute.value.name, (name) => {
  if (name == "notice"){
    // 获取页面数据
    getPageData()

  }
},{immediate: true,deep: true})

// 定义一个search变量，用于存储搜索关键字
const search = ref('')
// 定义一个计算属性filterTableData，用于根据search变量过滤tableData数据
// const filterTableData = computed(() =>
//     formData.filter(
//         (data) => !search.value ||data.name.toLowerCase().includes(search.value.toLowerCase())
//     )
// )

</script>
<style  scoped>
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 15px;
}
</style>